/**
 * Created with JetBrains WebStorm.
 * User: Rekey
 * Date: 13-9-27
 * Time: 上午1:33
 * To change this template use File | Settings | File Templates.
 */

var appPath = global.appPath;
var dao = require(appPath + '/dao/index.js');
var crypto = require(appPath + '/lib/crypto.js');
var config = require(appPath + '/config.js');

//设置登录的session啥的.
function gen_session(user, res) {
  var auth_token = crypto.encrypt(user._id + '\t' + user.name + '\t' + user.password + '\t' + user.mail, config.session_secret);
  res.cookie(config.auth_cookie_name, auth_token, {
    path: '/',
    maxAge: 1000 * 60 * 60 * 24 * 30,
    httpOnly: true
  });
  //cookie 有效期30天
}

//需要检测登录的中间件
function auth_user(req, res, next) {
  var t = Date.now();
  if (req.session.user) {
    //如果session里有用户数据
    console.log('req.session.user is defined.');
    res.locals.user = req.session.user;
    console.log('session存在 费时' + (Date.now() - t) + 'ms');
    t = null;
    next();
  } else {
    if (req.cookies.user) {
      //如果cookies里有用户信息,那就去取用户数据
      var user_arr = crypto.decrypt(req.cookies.user, config.session_secret).split('\t');
      console.log(user_arr);
      dao.user.getOneById(user_arr[0]).then(function (user) {
        console.log(user);
        //拿到了就丢到session里
        if (user) {
          req.session.user = user;
          res.locals.user = user;
        }
        console.log('cookie存在,查询存入session 费时' + (Date.now() - t) + 'ms');
        t = null;
        next();
      }, function (err) {
        //虽然cookies里有信息,但不是我们种下的
        if (err) {
          //如果有错就打印一下吧.
          console.log(err);
        }
        console.log('cookie存在,报错了 费时' + (Date.now() - t) + 'ms');
        t = null;
        next();
      });
    } else {
      //木有cookies,再见.
      console.log('木有cookies 费时' + (Date.now() - t) + 'ms');
      t = null;
      next();
    }
  }
}

//注册
function signup(req, res, next) {
  if (req.method == 'GET') {
    dao.category.getList().then(function (categories) {
      res.render('signup', {
        'title': 'Express',
        'categories': categories,
        'currentCategory': 'index'
      });
    });
  } else {
    var mail = req.body.mail.trim().toLowerCase();
    var password = req.body.password.trim().toLowerCase();
    if (mail && password) {
      dao.user.create({
        mail: mail,
        password: password
      }).then(function (user) {
        res.json(user);
      }, function (err) {
        console.log(err);
        next();
      });
    } else {
      next();
    }
  }
}

//登入逻辑
function signin(req, res, next) {
  if (req.method == 'GET') {
    //记录下登录的来源,如果没有就跳回首页
    /** @namespace req.headers.referer */
    req.session.loginReferer = req.headers.referer || '/';
    if (req.session.user) {
      res.redirect(req.session.loginReferer);
    } else {
      dao.category.getList().then(function (categories) {
        res.render('signin', {
          'title': 'Express',
          'categories': categories,
          'currentCategory': 'index'
        });
      });
    }
  } else {
    // 这是POST方法的处理
    var mail = req.body.mail.trim().toLowerCase();
    var password = req.body.password.trim().toLowerCase();
    if (!mail || !password) {
      res.json({
        'errno': 1,
        'message': '邮箱或密码错误'
      });
    } else {
      dao.user.getOneByMail(mail).then(function (user) {
        if (!user) {
          res.json({
            'errno': 1,
            'message': '邮箱或密码错误.'
          });
        } else {
          password = crypto.md5(crypto.md5(password) + user.salt);
          if (password == user.password) {
            gen_session(user, res);
            if (req.session.loginReferer) {
              res.redirect(req.session.loginReferer);
            } else {
              res.json({
                'errno': 0,
                'message': '登入成功'
              });
            }
          } else {
            res.json({
              'errno': 1,
              'message': '密码错误'
            });
          }
        }
      }, function (err) {
        return next(err);
      });
    }
  }
}

exports.signin = signin;
exports.signup = signup;
exports.auth_user = auth_user;